package grafico;

import gestores.GestorPago;

import javax.swing.JPanel;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JLabel;

import java.awt.Font;

import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.JPasswordField;
import javax.swing.JButton;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.JTextPane;

import java.awt.SystemColor;

import javax.swing.JRadioButton;
import javax.swing.JCheckBox;
import javax.swing.JToggleButton;

import java.awt.Cursor;
import java.lang.reflect.Array;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import logica.Consumo;
import logica.Estadia;
import logica.Excepcion;
import logica.Pasajero;
import logica.Responsablepago;

import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

import repositorio.DAOEstadia;

import javax.swing.ListSelectionModel;



public class Facturar_07_2 extends JPanel {
	private static final long serialVersionUID = 1L;
	private Double valorEstadia=0.0;
	private Double totalPagar=0.0;
	private JLabel lblTotalPagar;
	private JLabel lbliva;
	private JLabel lblPrecioneto;
	private String tipoFactura="";
	private List<Integer> consAfacturar = new ArrayList<>();
	private JTable table;
	private Robot robot ;
	private List<Consumo> consumos = new ArrayList<>();
	private JCheckBox chckbxValorEstadia;
	private Boolean[] consumosSeleccionados;
	private String nombre;
	
	/**
	 * Create the panel.
	 */
	public Facturar_07_2(PantallaPrincipal frame, String nroHabitacion, Pasajero pasajero, Responsablepago resPago, int idEstadiaFacturar, Calendar horaSalida, Facturar_07_1 facturar_1) {
			
				try{
				robot = new Robot();
				robot.keyPress(KeyEvent.VK_CONTROL);
				}
				catch (AWTException e) {e.printStackTrace();
				}

				setForeground(SystemColor.desktop);				
				setBackground(new Color(105, 105, 105));
				
				ImageIcon img=new ImageIcon(this.getClass().getResource("/imagenes/icono.jpg"));
				
				JLabel lblFacturar = new JLabel("Facturar");
				lblFacturar.setForeground(Color.WHITE);
				lblFacturar.setFont(new Font("Tahoma", Font.BOLD, 30));
				
				JLabel icono = new JLabel(img);
				
				JLabel lblNombre = new JLabel("Nombre:");
				lblNombre.setFont(new Font("Tahoma", Font.PLAIN, 17));
				lblNombre.setForeground(new Color(255, 102, 102));
				lblNombre.setBackground(new Color(255, 102, 102));
				
				JButton btnAceptar = new JButton("Aceptar");
				btnAceptar.setForeground(new Color(0, 102, 153));
				btnAceptar.setBackground(Color.LIGHT_GRAY);
				
				JLabel lblConsumos = new JLabel("Consumos habitaci\u00F3n:");
				lblConsumos.setForeground(Color.WHITE);
				lblConsumos.setFont(new Font("Tahoma", Font.BOLD, 14));
				
				JButton btnVolver = new JButton("Volver");
				btnVolver.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						robot.keyRelease(KeyEvent.VK_CONTROL);
						ingresar(frame);
					}

					
				});
				btnVolver.setForeground(new Color(0, 102, 153));
				btnVolver.setBackground(Color.LIGHT_GRAY);
				btnVolver.setFont(new Font("Tahoma", Font.PLAIN, 16));
				btnAceptar.setFont(new Font("Tahoma", Font.PLAIN, 16));
				
				chckbxValorEstadia = new JCheckBox("Valor estad\u00EDa");
				if(valorEstadia <=0) chckbxValorEstadia.setEnabled(false);
				chckbxValorEstadia.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
						if(chckbxValorEstadia.isSelected())
							seleccion(valorEstadia);
						if(chckbxValorEstadia.isSelected()==false)
							desseleccion(valorEstadia);
					}
				});
				chckbxValorEstadia.setFont(new Font("Tahoma", Font.BOLD, 14));
				chckbxValorEstadia.setForeground(new Color(255, 255, 255));
				chckbxValorEstadia.setBackground(new Color(105, 105, 105));
				
				GestorPago gPago = new GestorPago();
				if(gPago.estadiaFacturada(gPago.getFacturas(""+nroHabitacion)))
					chckbxValorEstadia.setEnabled(false);
				else{
					valorEstadia = gPago.calcularValorEstadia(idEstadiaFacturar, horaSalida);
					chckbxValorEstadia.setEnabled(true);
				}
				JLabel lblTipoDeFactura = new JLabel("Tipo de factura");
				lblTipoDeFactura.setForeground(Color.WHITE);
				lblTipoDeFactura.setFont(new Font("Tahoma", Font.BOLD, 14));
				
				
				JLabel lblPrecioNeto = new JLabel("Precio Neto");
				lblPrecioNeto.setForeground(Color.WHITE);
				lblPrecioNeto.setFont(new Font("Tahoma", Font.BOLD, 14));
				
				JLabel lblIva = new JLabel("IVA 21%");
				lblIva.setForeground(Color.WHITE);
				lblIva.setFont(new Font("Tahoma", Font.BOLD, 14));
				
				JLabel lblTotalAPagar = new JLabel("Total a pagar");
				lblTotalAPagar.setForeground(Color.WHITE);
				lblTotalAPagar.setFont(new Font("Tahoma", Font.BOLD, 14));
				
				JLabel label = new JLabel("..................................................................");
				
				JLabel lblPrecioEst = new JLabel("0.0");
				lblPrecioEst.setFont(new Font("Tahoma", Font.BOLD, 12));
				String precioEst = Double.toString(valorEstadia);
				lblPrecioEst.setText(precioEst);
				
				JLabel lblNewLabel = new JLabel(".................................................................");
				
				lblPrecioneto = new JLabel("0.0");
				lblPrecioneto.setFont(new Font("Tahoma", Font.BOLD, 12));
				lblPrecioneto.setText("0.0");
				
				JLabel label_4 = new JLabel("......................................................................");
				
				lbliva = new JLabel("0.0");
				lbliva.setFont(new Font("Tahoma", Font.BOLD, 12));
				lbliva.setText("0.0");
				
				JLabel label_5 = new JLabel(".......................................................................");
				
				lblTotalPagar = new JLabel("0.0");
				lblTotalPagar.setFont(new Font("Tahoma", Font.BOLD, 12));
				DecimalFormat df = new DecimalFormat("#.##");
				df.setRoundingMode(RoundingMode.DOWN);
				String totalpagarstring = df.format(totalPagar);
				lblTotalPagar.setText(totalpagarstring);
				
				JToggleButton tglbtnA = new JToggleButton("A");
				JToggleButton tglbtnB = new JToggleButton("B");
				
				JTextPane textPane = new JTextPane();
				textPane.setEditable(false);

				if(!(pasajero == null)){
					nombre = pasajero.getNombre()+" "+pasajero.getApellido();
					if(pasajero.getCuit() == null){
						tglbtnA.setEnabled(false);
						tglbtnB.setSelected(true);
						tipoFactura = "B";
						lblPrecioNeto.setEnabled(false);
						lblNewLabel.setEnabled(false);
						lblPrecioneto.setEnabled(false);
						lblIva.setEnabled(false);
						label_4.setEnabled(false);
						lbliva.setEnabled(false);
					}
					else{
						tglbtnB.setEnabled(false);
						tglbtnA.setSelected(true);
						tipoFactura = "A";
						lblPrecioNeto.setEnabled(true);
						lblNewLabel.setEnabled(true);
						lblPrecioneto.setEnabled(true);
						lblIva.setEnabled(true);
						label_4.setEnabled(true);
						lbliva.setEnabled(true);
					}
						
				}
				else{
					nombre = resPago.getRazonsocial();
					tglbtnB.setEnabled(false);
					tglbtnA.setSelected(true);
					tipoFactura = "A";
					lblPrecioNeto.setEnabled(true);
					lblNewLabel.setEnabled(true);
					lblPrecioneto.setEnabled(true);
					lblIva.setEnabled(true);
					label_4.setEnabled(true);
					lbliva.setEnabled(true);
				}
				textPane.setText(nombre);
				
				tglbtnA.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(tglbtnA.isSelected() == false)
							tipoFactura = "";
						if(tglbtnA.isSelected()){
							tipoFactura = "A";
							lblPrecioNeto.setEnabled(true);
							lblNewLabel.setEnabled(true);
							lblPrecioneto.setEnabled(true);
							lblIva.setEnabled(true);
							label_4.setEnabled(true);
							lbliva.setEnabled(true);
						}
					}
				});
				tglbtnB.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(tglbtnB.isSelected() == false)
							tipoFactura = "";
						if(tglbtnB.isSelected()){
							tipoFactura = "B";
							lblPrecioNeto.setEnabled(false);
							lblNewLabel.setEnabled(false);
							lblPrecioneto.setEnabled(false);
							lblIva.setEnabled(false);
							label_4.setEnabled(false);
							lbliva.setEnabled(false);
						}
					}
				});
				
				btnAceptar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent arg0) {
							robot.keyRelease(KeyEvent.VK_CONTROL);
							facturar(frame, idEstadiaFacturar, pasajero, resPago,facturar_1,horaSalida);
					}
				});
				
				JScrollPane scrollPane = new JScrollPane();
				
				GroupLayout groupLayout = new GroupLayout(this);
				groupLayout.setHorizontalGroup(
					groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addContainerGap(667, Short.MAX_VALUE)
							.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
								.addComponent(btnAceptar, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
								.addComponent(btnVolver, Alignment.LEADING, GroupLayout.PREFERRED_SIZE, 97, GroupLayout.PREFERRED_SIZE))
							.addGap(62))
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(75)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addGroup(groupLayout.createSequentialGroup()
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addGroup(groupLayout.createSequentialGroup()
											.addGap(32)
											.addGroup(groupLayout.createParallelGroup(Alignment.LEADING, false)
												.addGroup(groupLayout.createSequentialGroup()
													.addComponent(lblPrecioNeto, GroupLayout.PREFERRED_SIZE, 84, GroupLayout.PREFERRED_SIZE)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(lblNewLabel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
												.addGroup(groupLayout.createSequentialGroup()
													.addComponent(lblIva)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(label_4)))
											.addPreferredGap(ComponentPlacement.RELATED, 367, GroupLayout.PREFERRED_SIZE))
										.addGroup(groupLayout.createSequentialGroup()
											.addComponent(lblTipoDeFactura)
											.addPreferredGap(ComponentPlacement.RELATED)
											.addComponent(tglbtnA)
											.addPreferredGap(ComponentPlacement.RELATED)
											.addComponent(tglbtnB))
										.addGroup(groupLayout.createSequentialGroup()
											.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
												.addGroup(groupLayout.createSequentialGroup()
													.addComponent(lblTotalAPagar, GroupLayout.PREFERRED_SIZE, 92, GroupLayout.PREFERRED_SIZE)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(label_5)
													.addPreferredGap(ComponentPlacement.RELATED)
													.addComponent(lblTotalPagar, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
												.addGroup(Alignment.LEADING, groupLayout.createSequentialGroup()
													.addGap(388)
													.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING, false)
														.addComponent(lbliva, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
														.addComponent(lblPrecioneto, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 109, Short.MAX_VALUE))))
											.addGap(254)))
									.addContainerGap())
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 508, GroupLayout.PREFERRED_SIZE)
									.addContainerGap())
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(lblConsumos)
									.addContainerGap())
								.addGroup(groupLayout.createSequentialGroup()
									.addComponent(chckbxValorEstadia)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(label)
									.addPreferredGap(ComponentPlacement.RELATED)
									.addComponent(lblPrecioEst, GroupLayout.PREFERRED_SIZE, 112, GroupLayout.PREFERRED_SIZE)
									.addContainerGap())
								.addGroup(groupLayout.createSequentialGroup()
									.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
										.addComponent(lblFacturar)
										.addGroup(groupLayout.createSequentialGroup()
											.addComponent(lblNombre)
											.addPreferredGap(ComponentPlacement.RELATED)
											.addComponent(textPane, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)))
									.addGap(356)
									.addComponent(icono)
									.addGap(105))))
				);
				groupLayout.setVerticalGroup(
					groupLayout.createParallelGroup(Alignment.LEADING)
						.addGroup(groupLayout.createSequentialGroup()
							.addGap(7)
							.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
								.addComponent(icono, GroupLayout.PREFERRED_SIZE, 141, GroupLayout.PREFERRED_SIZE)
								.addGroup(groupLayout.createSequentialGroup()
									.addGap(52)
									.addComponent(lblFacturar)
									.addGap(43)
									.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
										.addComponent(lblNombre)
										.addComponent(textPane, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))))
							.addGap(18)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(chckbxValorEstadia)
								.addComponent(label)
								.addComponent(lblPrecioEst))
							.addGap(18)
							.addComponent(lblConsumos)
							.addGap(18)
							.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 147, GroupLayout.PREFERRED_SIZE)
							.addGap(38)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblTipoDeFactura, GroupLayout.PREFERRED_SIZE, 17, GroupLayout.PREFERRED_SIZE)
								.addComponent(tglbtnA)
								.addComponent(tglbtnB))
							.addGap(18)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblPrecioNeto, GroupLayout.PREFERRED_SIZE, 17, GroupLayout.PREFERRED_SIZE)
								.addComponent(lblNewLabel)
								.addComponent(lblPrecioneto))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblIva, GroupLayout.PREFERRED_SIZE, 17, GroupLayout.PREFERRED_SIZE)
								.addComponent(label_4)
								.addComponent(lbliva))
							.addGap(18)
							.addGroup(groupLayout.createParallelGroup(Alignment.BASELINE)
								.addComponent(lblTotalAPagar, GroupLayout.PREFERRED_SIZE, 17, GroupLayout.PREFERRED_SIZE)
								.addComponent(label_5)
								.addComponent(lblTotalPagar))
							.addGap(45)
							.addComponent(btnAceptar, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(btnVolver, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
							.addGap(42))
				);

				table = new JTable();
				table.setFocusCycleRoot(true);
				table.setFocusTraversalPolicyProvider(true);
				table.setSurrendersFocusOnKeystroke(true);

				DefaultTableModel modelo =(new DefaultTableModel(
					new Object[][] {
					},
					new String[] {
						"Producto", "Cantidad", "Precio Total"
					}
				) {
					/**
					 * 
					 */
					private static final long serialVersionUID = 1L;
					Class[] columnTypes = new Class[] {
						String.class, Integer.class, Float.class
					};
					public Class getColumnClass(int columnIndex) {
						return columnTypes[columnIndex];
					}
					boolean[] columnEditables = new boolean[] {
						false, false, false
					};
					public boolean isCellEditable(int row, int column) {
						return columnEditables[column];
					}
				});
				table.setModel(modelo);
				table.getColumnModel().getColumn(0).setResizable(false);
				table.getColumnModel().getColumn(1).setResizable(false);
				table.getColumnModel().getColumn(2).setResizable(false);
				
				scrollPane.setViewportView(table);
				setLayout(groupLayout);

				consumos = gPago.consumosSinFacturar(idEstadiaFacturar);
				consumosSeleccionados = new Boolean[consumos.size()]; 
				int i=0;
				for (Consumo consumo : consumos) {
					consumosSeleccionados[i] = false;
					i++;
					double precioTotalCons = consumo.getCantidad()*consumo.getPrecio();
					modelo.addRow(new Object[] {consumo.getProducto().getDescripcion(), consumo.getCantidad(),
												precioTotalCons});
				}
				
				table.addMouseListener(new MouseAdapter() {
					@Override
					public void mouseClicked(MouseEvent arg0) {
						int[] nros = table.getSelectedRows();
						incrementarTotal(nros);
					}
				});
				
				
			}
			
			private void seleccion(double valor){
				totalPagar += valor;
				setLbls();
			}
			private void desseleccion(double valor){
				totalPagar -= valor;
				setLbls();
			}

			private void setLbls(){
				DecimalFormat df = new DecimalFormat("#.##");
				df.setRoundingMode(RoundingMode.DOWN);
				
				String precionetostr = df.format(totalPagar*0.79);
				lblPrecioneto.setText(precionetostr);
				String ivastr = df.format(totalPagar*0.21);
				lbliva.setText(ivastr);
				String totalpagarstring = df.format(totalPagar);
				lblTotalPagar.setText(totalpagarstring);
			}
			
			private void facturar(PantallaPrincipal frame,int idEstadiaFacturar, Pasajero pasajero, Responsablepago resPago, Facturar_07_1 facturar_1, Calendar horaSalida){
				try{
					GestorPago gPago = new GestorPago();
				
				
				int[] filasSeleccionadas = table.getSelectedRows();
				for (int j : filasSeleccionadas) {
					Consumo cons = consumos.get(j);
					consAfacturar.add(cons.getIdConsumo());
				}
				if(tipoFactura.equals(""))
					throw new Excepcion("Seleccionar una tipo de factura");
				if(chckbxValorEstadia.isSelected()){
					gPago.facturar(idEstadiaFacturar, pasajero, resPago, nombre, consAfacturar, tipoFactura, totalPagar,true);
				}
				
				else{
					gPago.facturar(idEstadiaFacturar, pasajero,resPago, nombre, consAfacturar, tipoFactura, totalPagar,false);
				}
				if(gPago.isFacturada(idEstadiaFacturar)){
					gPago.estadiaFacturada(horaSalida,idEstadiaFacturar);
					ingresar(frame);
				}
				else{
					JOptionPane.showInternalMessageDialog(this,  "Faltan items a facturar. Generar una factura para tales.");
					facturar_1.reiniciar();
					facturar_1.setVisible(true);
					frame.setContentPane(facturar_1);
					this.setVisible(false);
					
				}}
				catch(Excepcion e){JOptionPane.showInternalMessageDialog(this,e.getDescripcion());}
			
			}

			
			
			
			private void ingresar(PantallaPrincipal frame) {
				this.setVisible(false);
				frame.setContentPane(new Menu(frame));
				
			}
			private void incrementarTotal(int[] nros){
				for(int i =0; i<consumos.size();i++){
				
					Consumo consumo = consumos.get(i);
					double valor = consumo.getCantidad()*consumo.getPrecio();
					if(!consumosSeleccionados[i] && contiene(i,nros) ){
						
						consumosSeleccionados[i]=true;
						seleccion(valor);
					}
					else if(consumosSeleccionados[i] && !contiene(i,nros)){
						consumosSeleccionados[i]=false;
						desseleccion(valor);
						
					}
				}
			}
			
			private boolean contiene(int i, int[] nros){
				for(int n :nros){
					if(n==i)
						return true;
				}
				return false;
			}
			
}
